import {
	Button,
	Checkbox,
	Form,
	Input,
	InputNumber,
	Modal,
	Table,
	message,
} from "antd";
import { useForm } from "antd/es/form/Form";
import { ColumnsType } from "antd/es/table";
import { FriendshipSearchResult } from "../Friendship";
import { useEffect, useMemo, useState } from "react";
import { userFriendshipServer } from "@/servers/userServer";
import { canJoinServer, joinChatServer } from "@/servers/chatroomServer";

interface JoinModalProps {
	chatroomId: number;
	isOpen: boolean;
	handleClose: Function;
}

const layout = {
	labelCol: { span: 6 },
	wrapperCol: { span: 18 },
};

export interface AddMember {
	username: string;
}

export default function JoinModal(props: JoinModalProps) {


	const handleOk = async function () {
		try {
            let userIds = friendshipResult.filter(item => item.isJoin).map(item => item.id)
            const res = await joinChatServer(props.chatroomId , userIds)
            const { code , data , message:msg } = res.data
            console.log(code , data);
            if(code === 200 || code === 201){
                await getCanJoin(props.chatroomId);
                message.success(msg)
                props.handleClose()
            } 
            
            
            
		} catch (e: any) {
			message.error(e.response?.data?.message || "系统繁忙，请稍后再试");
		}
	};


    const changeIsJoin = (id:number) => {
        setFriendshipResult((prevResult) =>prevResult.map((item) => item.id === id? {...item, isJoin:!item.isJoin } :item));
    }

	const [friendshipResult, setFriendshipResult] = useState<Array<FriendshipSearchResult>>([]);
	const getCanJoin = async (chatroomId:number) => {
		const res = await canJoinServer(chatroomId);
		const { code, data, message: msg } = res.data;
        console.log(data);
        
		if (code === 200 || code === 201) {
			setFriendshipResult(data);
		} else {
			message.error(msg);
		}
	};
	useEffect(() => {
		getCanJoin(props.chatroomId);
	}, [props.chatroomId]);

	const columns: ColumnsType<FriendshipSearchResult> = useMemo(
		() => [
			{
				title: "昵称",
				dataIndex: "username",
			},
			{
				title: "头像",
				dataIndex: "headPic",
				render: (_, record) => (
					<div>
						<img src={record.headPic} />
					</div>
				),
			},
			{
				title: "邮箱",
				dataIndex: "email",
			},
			{
				title: "操作",
				render: (_, record) => (
					<div>
						<Checkbox
							checked={record.isJoin}
							onChange={() => changeIsJoin (record.id)}
						></Checkbox>
					</div>
				),
			},
		],
		[]
	);
	return (
		<Modal
			title="添加成员"
			open={props.isOpen}
			onOk={handleOk}
			onCancel={() => props.handleClose()}
			okText={"添加"}
			cancelText={"取消"}
		>
			<Table
				columns={columns}
				dataSource={friendshipResult}
				rowKey={(record) => record.id}
				style={{ width: "1000px" }}
			/>
		</Modal>
	);
}
